#include "widget.h"

void Widget::SerialPort_Open()
{
	isSPopen = true;
	btnOpen->setText("断开连接");
	cbbxBaudrate->setEnabled(false);
	cbbxPort->setEnabled(false);
	lblVersion->setText(version);
}

void Widget::SerialPort_Close()
{
	serialPort->close();
	isSPopen = false;
	btnOpen->setText("打开连接");
	cbbxBaudrate->setEnabled(true);
	cbbxPort->setEnabled(true);
	tmr100ms->stop();
}

void Widget::SerialPort_Scan()
{
	QStringList PortsName;
	foreach(const QSerialPortInfo & info, QSerialPortInfo::availablePorts())
		PortsName += info.portName();
	if (PortsName == PreviousPortsName) return;  //可用端口未发生变化
	if (!isSPopen) {  //当前端口处于关闭状态
		cbbxPort->clear();
		cbbxPort->addItems(PortsName);
	}
	else if (cbbxPort->findText(serialPort->portName()) == -1)  //串口设备被强制拔出
		SerialPort_Close();
	else {
		cbbxPort->clear();
		cbbxPort->addItem(serialPort->portName());
		foreach(QString port, PortsName) {
			if (port != serialPort->portName())
				cbbxPort->addItem(port);
		}
	}
	PreviousPortsName = PortsName;
}

void Widget::SerialPort_Receive()
{
	u8 RcvCnt = 0;
	QByteArray buf = serialPort->readAll();
	if (buf.isEmpty()) return;
	for (int i = 0; i < buf.size(); ++i) {
		if (serialPort->Data_Receive_Precess(buf[i]) == 0) {
			RcvCnt++;
			break;
		}
	}
	if (!RcvCnt) return;
	u8 RxTemp[12];
	short datatemp;
	serialPort->RcvdData(RxTemp);
	switch (serialPort->RcvdFcn()) {
	case MAX_SPEED:
		for (int i = 0; i < 6; ++i) {
			datatemp = (RxTemp[i << 1] << 8) + RxTemp[(i << 1) + 1];
			ledt2JointSpeed[i]->setText(QString::number(datatemp));
		}
		break;
	case MAX_ACC:
		for (int i = 0; i < 6; ++i) {
			datatemp = (RxTemp[i << 1] << 8) + RxTemp[(i << 1) + 1];
			ledt2JointAccelerate[i]->setText(QString::number(datatemp));
		}
		break;
    case REQ_ADC:
        datatemp = (RxTemp[0] << 8) + RxTemp[1];
        if (datatemp >= 2200)
            Slot_btnEmergencyStop_Click();
        lbl4Coordinates[6]->setNum((int)datatemp);
        if (ckbx4Options[4]->isChecked())
            pressfile.Save_Data(datatemp);
        break;
	case REQUIRE:
		datatemp = RxTemp[0];
        if (datatemp == 0){
            for (int i = 0; i < 6; ++i)
                lbl2CalibrateFlag[i]->setNum(0);
            break;
        }
		for (int i = 0; i < 6; ++i){
			if (datatemp & (1 << i)){
				lbl2CalibrateFlag[i]->setNum(1);
                slid1Tuning1[i]->setValue(0);
                slid1Tuning2[i]->setValue(0);
                slid1Tuning3[i]->setValue(0);
            }
        }
        break;
    default: break;
	}
	RcvCnt--;
}
